package com.springboot.redis.demo.geohash;

import com.springboot.redis.demo.RedisClient;
import redis.clients.jedis.GeoRadiusResponse;
import redis.clients.jedis.GeoUnit;

import java.util.ArrayList;
import java.util.List;

/**
 * 查找附近的人案例
 *
 * @author: zr
 * @date: 2021-11-17
 */
public class NeerByUsersDemo extends RedisClient {

    /**
     * 获取Redis Key
     *
     * @return {@link String}
     * @throws
     * @date 2021-11-17
     */
    public static String getKey() {
        return "location_data";
    }

    /**
     * 添加一个地理位置
     *
     * @param name
     * @param longitude
     * @param latitude
     * @return
     * @throws
     * @date 2021-11-17
     */
    public static void addLocation(String name, double longitude, double latitude) {
        jedis.geoadd(getKey(), longitude, latitude, name);
    }

    /**
     * 查找附近N公里的商家
     *
     * @param
     * @return {@link List< GeoRadiusResponse>}
     * @throws
     * @date 2021-11-17
     */
    public static List<GeoRadiusResponse> getNearByShorps(String name, int radius) {
        return jedis.georadiusByMember(getKey(), name, radius, GeoUnit.KM);
    }

    public static void main(String[] args) {
        addLocation("张三", 116.494288, 39.8670046);
        addLocation("小吃店", 116.459612, 39.8751730);
        List<String> nearByShops = new ArrayList<>();

        /** 多大范围，这里表示5公里*/
        int radius = 5;
        String userName = "张三";
        List<GeoRadiusResponse> responses = getNearByShorps(userName, radius);
        for (GeoRadiusResponse response : responses) {
            String name = response.getMemberByString();
            if (!name.equals("张三")) {
                nearByShops.add(name);
            }
        }
        System.out.println("附近" + radius + "公里的商家：" + nearByShops);
    }
}
